#include<stdio.h>
#include<string.h>

#define MaxSize 50
typedef int Elem_type;

typedef struct
{
    Elem_type *data;//原定义是Elem_type data[MaxSize],但data是常量，无法用malloc给它赋值
    int length;
    
}Sqlist_type;


void initList(Sqlist_type *L)
{

    L->length = 0;
}

Sqlist_type* initList2(void){

    Sqlist_type *list;
    list = (Sqlist_type *)malloc(sizeof(Sqlist_type));
    list->data = (Elem_type *)malloc(sizeof(Elem_type) * MaxSize);//此处data就是个指针变量，如果是数组名就无法赋值了，因为数组名是指针常量
    list->length = 0;

    return list;

}
int appendElem(Sqlist_type *L, Elem_type e)
{
    if(L->length>=MaxSize)
    {
        printf("顺序表已经满");
        return 0;
    }

    L->data[L->length] = e;
    L->length++;
    return 1;
}

void listElem(Sqlist_type *L){

    for(int i =0; i<L->length;i++){
        printf("%d ",L->data[i]);
    }
    printf("\n");
}

int insertElem(Sqlist_type *L,int PosNum,Elem_type e){

    int i;
     //插入位置合法性检查
     if(L->length>= MaxSize){

        printf("位置已满，无法插入");
        return 0;
     }

     if(PosNum<1 || PosNum>L->length){

        printf("插入位置错误");
        return 0;
     }
    if(1<=PosNum<=L->length){

        for(i=L->length-1;i>=PosNum-1;i--)
        {
            L->data[i+1]=L->data[i];
        }
        L->data[PosNum-1]=e;
        L->length++;

        return 1;
    }


}

int deleteElem(Sqlist_type *L,int PosNum,Elem_type *e){

    if(L->length==0){
        printf("表为空");
        return 0;
    }  

    if(PosNum<1 || PosNum >L->length){

        printf("删除数据位置错误");
        return 0;
    }

    *e = L->data[PosNum-1];

    if(PosNum < L->length){

        for(int i=PosNum;i<L->length;i++){

            L->data[i-1]=L->data[i];
        }
    }

        L->length--;
        return 1;
}


int main(int argc,char const *argv[]){

    //声明一个线性表，并初化
    Sqlist_type *list = initList2();
   
    printf("初始化成功，目前长度占用%d\n",(*list).length);
    printf("目前占用内存%zu字节\n",sizeof(*list).data);
    appendElem(list,88);
    appendElem(list,32);
    appendElem(list,21);
    appendElem(list,14);

    listElem(list);
    insertElem(list, 2, 7);
    listElem(list);

    Elem_type deleteData;
    
    deleteElem(list, 2, &deleteData);

    printf("删除的数据是%d\n",deleteData);
    listElem(list);


    return 0;
}

